﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PeoplesJukebox.Core.Interfaces;
using PeoplesJukebox.Core.MediaItems;
using Microsoft.DirectX.AudioVideoPlayback;
using System.Threading;
using PeoplesJukebox.Core.Logging;

namespace PeoplesJukebox.Core.Players
{
    public class DirectXPlayer : IMediaPlayer
    {
        private static Track _currentTrack;
        private static Audio _audio;

        static DirectXPlayer()
        {
            _currentTrack = PeoplesJukeboxService.GetNextTrack();
            if (_currentTrack != null)
            {
                _audio = new Audio(_currentTrack.Uri);
                _audio.Ending += OnAudioEnding;
                _audio.Stopping += new EventHandler(OnAudioStopping);
            }
        }

        

        public Track CurrentTrack
        {
            get { return _currentTrack; }
        }

        public void Start()
        {
            PlayNext();
        }

        static void PlayNext()
        {
            if (_currentTrack != null)
            {
                try
                {
                    StopInternal();
                    ThreadPool.QueueUserWorkItem(PlayCallback, _currentTrack);
                }
                catch (Exception ex)
                {
                    Log.Error("DirectXPlayer.PlayNext errored: {0}", ex.Message);
                }
            }
            _currentTrack = PeoplesJukeboxService.GetNextTrack();
        }

        static void PlayCallback(object state)
        {
            Track nextTrack = state as Track;
            Log.Info("DirectXPlayer.PlayCallback, new URL={0}", nextTrack.Uri);
            try
            {
                _audio.Open(nextTrack.Uri);
                //0 = max; -10000 = silence:
                _audio.Volume = -100;
                _audio.Play();
                Log.Info("DirectXPlayer.PlayCallback, called Play()");
            }
            catch (Exception ex)
            {
                Log.Error("DirectXPlayer.PlayCallback errored: {0}", ex.Message);
            }            
        }

        public void Skip()
        {
            PlayNext();
        }

        public void Stop()
        {
            StopInternal();
        }

        static void StopInternal()
        {
            if (_audio != null)
            {
                if (_audio.Playing)
                {
                    _audio.Stop();
                }
            }
        }

        static void OnAudioEnding(object sender, EventArgs e)
        {
            Log.Info("DirectXPlayer.OnAudioEnding called");
            PlayNext();
        }

        static void OnAudioStopping(object sender, EventArgs e)
        {
            Log.Info("DirectXPlayer.OnAudioStopping called");
        }
    }
}
